<?php
include_once('BCGFontFile.php');
include_once('BCGDrawing.php');
include_once('BCGcode128.barcode.php');
include_once('BCGColor.php');
class Barcode
{
    public $colorFront;
    public $colorBlack;
    public $font;

    function __construct()
    {
        $this->colorBlack = new BCGColor(255, 255, 255);
        $this->colorFront = new BCGColor(0, 0, 0);
        $this->font       = new BCGFontFile(dirname(__FILE__) . "/font/msyh.ttf", 16); //需要字体在这里指定
    }

    /**
     * 生成条形码，text为内容，$save为是否保存条形码图，0直接输入到浏览器，1保存图片
     **/
    public function get_barcode($text, $save = 1)
    {
        $code = new BCGcode128();
        $code->setScale(2); // Resolution
        $code->setThickness(30); // Thickness
        $code->setForegroundColor($this->colorFront); // Color of bars
        $code->setBackgroundColor($this->colorBlack); // Color of spaces
        $code->setFont($this->font); // Font (or 0)
        $code->parse($text); // Text
        $save    = empty($save) ? '' : dirname(__FILE__) . '/../../upload/Barcode/' . $text . '.png';

        $drawing = new BCGDrawing($save, $this->colorBlack); //生成二维码文件
        $drawing->setBarcode($code);
        $drawing->draw();

        //如果不保存图片就直接输入到浏览器
        if (empty($save)) {
            header('Content-Type: image/png');
        }

        $drawing->finish((BCGDrawing::IMG_FORMAT_PNG));
        $imgpath = '/upload/Barcode/' . $text . '.png';
        return $imgpath;
    }
}